package com.qianli.cashmama.trade.repo.impl;

import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.qianli.cashmama.trade.common.enums.TaskStatusEnum;
import com.qianli.cashmama.trade.common.enums.TaskTypeEnum;
import com.qianli.cashmama.trade.dao.TTaskCenterDao;
import com.qianli.cashmama.trade.dao.TTaskRecordDao;
import com.qianli.cashmama.trade.domain.model.TradeTaskCenter;
import com.qianli.cashmama.trade.entity.TTaskCenterEntity;
import com.qianli.cashmama.trade.entity.TTaskRecordEntity;
import com.qianli.cashmama.trade.repo.TradeTaskCenterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/22
 * Time: 下午4:18
 */
@Repository
public class TradeTaskCenterRepositoryImpl implements TradeTaskCenterRepository {
    @Autowired
    private TTaskCenterDao tTaskCenterDao;

    @Autowired
    private TTaskRecordDao tTaskRecordDao;


    @Override
    public Long store(TradeTaskCenter tradeTaskCenter) {
        TTaskCenterEntity tTaskCenterEntity = new TTaskCenterEntity()
                .setBizNo(tradeTaskCenter.getBizNo())
                .setTaskRetryTimes(tradeTaskCenter.getTaskRetryTimes())
                .setTaskStatus(tradeTaskCenter.getTaskStatus().getStatus())
                .setTaskType(tradeTaskCenter.getTaskType().getType())
                .setResultMsg(tradeTaskCenter.getResultMsg())
                .setTradeNo(tradeTaskCenter.getTradeNo());
        TTaskCenterEntity entity = tTaskCenterDao.insert(tTaskCenterEntity);
        return entity.getId();
    }

    @Override
    public List<TradeTaskCenter> selectWaitingListByPageAndType(TaskTypeEnum typeEnum, Page page, Integer retryCount) {
        List<Integer> status = new ArrayList<>(2);
        status.add(TaskStatusEnum.INIT.getStatus());
        status.add(TaskStatusEnum.FAILED.getStatus());
        if (retryCount == null) {
            retryCount = 30;
        }

        List<TTaskCenterEntity> tTaskCenterEntityList = tTaskCenterDao.selectListByStatusAndTypeAndPage(status, typeEnum.getType(), retryCount, page);
        if (CollectionUtils.isEmpty(tTaskCenterEntityList)) {
            return null;
        }
        List<TradeTaskCenter> tradeTaskCenterList = new ArrayList<>();
        for (TTaskCenterEntity entity : tTaskCenterEntityList) {
            TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                    .setId(entity.getId())
                    .setBizNo(entity.getBizNo())
                    .setTradeNo(entity.getTradeNo())
                    .setTaskType(TaskTypeEnum.getByType(entity.getTaskType()))
                    .setTaskRetryTimes(entity.getTaskRetryTimes());

            tradeTaskCenterList.add(tradeTaskCenter);
        }

        return tradeTaskCenterList;
    }

    @Override
    public List<TradeTaskCenter> selectTradeTaskList(String tradeNo, TaskTypeEnum taskTypeEnum) {
        Map<String, Object> params = Maps.newConcurrentMap();
        params.put("tradeNo", tradeNo);
        params.put("deleted", 0);
        params.put("taskType", taskTypeEnum.getType());
        List<TTaskCenterEntity> tTaskCenterEntityList = tTaskCenterDao.selectByParams(params);
        if (CollectionUtils.isEmpty(tTaskCenterEntityList)) {
            return null;
        }
        List<TradeTaskCenter> tradeTaskCenterList = new ArrayList<>();
        for (TTaskCenterEntity entity : tTaskCenterEntityList) {
            TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                    .setId(entity.getId())
                    .setBizNo(entity.getBizNo())
                    .setTradeNo(entity.getTradeNo())
                    .setTaskType(TaskTypeEnum.getByType(entity.getTaskType()))
                    .setTaskRetryTimes(entity.getTaskRetryTimes());

            tradeTaskCenterList.add(tradeTaskCenter);
        }
        return tradeTaskCenterList;
    }

    @Override
    public void update(TradeTaskCenter tradeTaskCenter) {
        TTaskCenterEntity tTaskCenterEntity = new TTaskCenterEntity()
                .setBizNo(tradeTaskCenter.getBizNo())
                .setTaskRetryTimes(tradeTaskCenter.getTaskRetryTimes())
                .setTaskStatus(tradeTaskCenter.getTaskStatus().getStatus())
                .setTaskType(tradeTaskCenter.getTaskType().getType())
                .setResultMsg(tradeTaskCenter.getResultMsg())
                .setTradeNo(tradeTaskCenter.getTradeNo());

        tTaskCenterEntity.setId(tradeTaskCenter.getId());
        tTaskCenterDao.updateByPrimaryKey(tTaskCenterEntity);
    }


    @Override
    public String getTaskRecord(Long taskId) {
        TTaskRecordEntity entity = getTaskRecordEntity(taskId);
        return Objects.nonNull(entity) ? entity.getRequest() : "";

    }

    @Override
    public void updateTaskRecord(Long taskId, String rspMsg) {
        TTaskRecordEntity entity = getTaskRecordEntity(taskId);
        Optional.ofNullable(entity).ifPresent(entity1 -> {
            entity1.setResponse(Strings.nullToEmpty(rspMsg));
            tTaskRecordDao.updateByPrimaryKey(entity1);
        });
    }

    private TTaskRecordEntity getTaskRecordEntity(Long taskId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("deleted", 0);
        params.put("taskId", taskId);
        List<TTaskRecordEntity> tTaskRecordEntities = tTaskRecordDao.selectByParams(params);
        if (CollectionUtils.isEmpty(tTaskRecordEntities)) {
            return null;
        }
        List<TTaskRecordEntity> collect = tTaskRecordEntities.stream().sorted(Comparator.comparing(TTaskRecordEntity::getId).reversed())
                .collect(Collectors.toList());
        return collect.get(0);
    }

    @Override
    public void delete(TradeTaskCenter tradeTaskCenter) {
        tTaskCenterDao.deleteByPrimaryKey(tradeTaskCenter.getId());
    }
}
